package com.zy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.constant.ProductConstants;
import com.zy.domain.Prod;
import com.zy.domain.ProdTag;
import com.zy.domain.ProdTagReference;
import com.zy.domain.Sku;
import com.zy.mapper.ProdTagReferenceMapper;
import com.zy.mapper.SkuMapper;
import com.zy.service.ProdService;
import com.zy.mapper.ProdMapper;
import com.zy.service.ProdTagReferenceService;
import com.zy.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author RASH_ZY
 * @description 针对表【prod(商品)】的数据库操作Service实现
 * @createDate 2025-04-02 11:54:04
 */
@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod>
        implements ProdService {

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;


    @Autowired
    private ProdTagReferenceMapper prodTagReferenceMapper;

    @Autowired
    private SkuService skuService;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 新增商品
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveProd(Prod prod) {
        //设置商品信息
        prod.setShopId(1L);
        prod.setSoldNum(0);
        prod.setCreateTime(new Date());
        prod.setUpdateTime(new Date());
        prod.setPutawayTime(new Date());
        prod.setVersion(0);
        //获取配送方式
        //前端以对象的方式传给后端，通过内部类接收
        Prod.DeliveryModeVo deliveryModeVo = prod.getDeliveryModeVo();
        //配送方式转JSON字符串写入商品信息
        prod.setDeliveryMode(JSONObject.toJSONString(deliveryModeVo));

        //新增商品信息
        int insert = prodMapper.insert(prod);

        if (insert > 0) {
            //商品添加成功

            //1.添加商品分组标签
            //创建标签与商品关系集合
            List<ProdTagReference> tagReferenceList = new ArrayList<>();
            List<Long> tagList = prod.getTagList();
            if (CollectionUtil.isNotEmpty(tagList) && tagList.size() != 0) {
                //遍历商品分组标签集合
                tagList.forEach(tag -> {
                    //设置商品分组标签与商品的关系信息
                    ProdTagReference tagReference = new ProdTagReference();
                    tagReference.setShopId(1L);
                    tagReference.setTagId(tag);
                    tagReference.setProdId(prod.getProdId());
                    tagReference.setStatus(1);
                    tagReference.setCreateTime(new Date());
                    //将标签与商品关系写入标签与商品关系集合
                    tagReferenceList.add(tagReference);
                });
            }
            //批量添加商品分组标签
            prodTagReferenceService.saveBatch(tagReferenceList);

            //2.添加商品sku
            //获取商品sku集合
            List<Sku> skuList = prod.getSkuList();
            if (CollectionUtil.isNotEmpty(skuList) && skuList.size() != 0) {
                //遍历商品sku集合
                skuList.forEach(sku -> {
                    //设置商品sku信息
                    sku.setProdId(prod.getProdId());
                    sku.setCreateTime(new Date());
                    sku.setUpdateTime(new Date());
                    sku.setVersion(0);
                    sku.setActualStocks(sku.getStocks());
                });
                skuService.saveBatch(skuList);
            }
        }
        return insert>0;
    }

    /**
     * 根据标识查询商品详情
     * @param prodId
     * @return
     */
    @Override
    public Prod queryProdInfoById(Long prodId) {
        //1.根据prodId获取商品对象信息
        Prod prod = prodMapper.selectById(prodId);
        if (ObjectUtil.isNull(prod)) {
            //没有商品信息直接返回
            return prod;
        }

        //2.为商品对象填充标签关系集合信息
        //获取商品与标签关系集合
        List<ProdTagReference> prodTagReferenceList = prodTagReferenceMapper.selectList(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prodId)
        );
        //从商品与标签关系集合中获取标签id
        List<Long> tagIdList = prodTagReferenceList.stream()
                .map(ProdTagReference::getTagId)
                .collect(Collectors.toList());
        //tagId写入商品对象
        prod.setTagList(tagIdList);

        //3.为商品对象填sku集合信息
        List<Sku> skuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId));
        prod.setSkuList(skuList);
        return prod;
    }

    /**
     * 修改商品信息
     *  1.删除原有的商品标签关系
     *  2.批量新增商品标签关系
     *  3.修改sku
     *  4.修改商品信息
     * @param prod
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyProdInfo(Prod prod) {
        //1.删除原有的商品标签关系
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, prod.getProdId()));
        //获取商品标签Id集合
        List<Long> tagIdList = prod.getTagList();
        List<ProdTagReference> tagReferenceList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(tagIdList) && tagIdList.size() >0) {
            tagIdList.forEach(tagId -> {
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setProdId(prod.getProdId());
                prodTagReference.setTagId(tagId);
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setShopId(1L);
                prodTagReference.setStatus(1);
                tagReferenceList.add(prodTagReference);
            });
        }

        //2.批量新增商品标签关系
        prodTagReferenceService.saveBatch(tagReferenceList);

        //3.修改sku(sku表)
        //设置sku属性
        List<Sku> skuList = prod.getSkuList();
        skuList.forEach(sku -> {
            sku.setUpdateTime(new Date());
            sku.setActualStocks(sku.getStocks());
        });
        //修改sku
        skuService.updateBatchById(skuList);

        //4.修改商品信息
        prod.setUpdateTime(new Date());
        return prodMapper.updateById(prod) > 0;
    }

}




